import { useState, useEffect, useCallback, useRef } from 'react';
import { Select, Input, Space, Button } from 'antd';
import {
  CaretDownOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons';
import { getMessage } from '@inbiz/react';
import './index.less';
const Option = Select.Option;

const ModalPagination = (props: {
  options?: number[]; // 分页可选择数量数组
  total?: number; // 记录总数
  current?: number; // 当前页码
  pageSize?: number; // 默认分页的单页记录数量
  onChange?: Function;
  style?: object; // 内联样式
  className?: string; // 分页器类名
}) => {
  // 记录总数
  const [total, $total] = useState<number>(0);
  // 当前页码
  const [current, $current] = useState<number>(1);
  // 分页量
  const [pageSize, $pageSize] = useState<number>(10);
  // 总页数
  const [pageCount, $pageCount] = useState(0);
  // 分段值
  const [section, $section] = useState('');
  // 跳页当前页
  const [jumpCurrent, $jumpCurrent] = useState<number | string>(1);

  // 输入框对象
  const iptObj = useRef<any>();

  // 内部触发onChange许可
  const shouldChange = useRef<boolean>();

  // 同步更新记录总数
  useEffect(() => {
    $total(props.total || 0);
  }, [props.total]);

  // 同步更新当前页码
  useEffect(() => {
    props.current && $current(props.current);
    props.current && $jumpCurrent(props.current);
  }, [props.current]);

  // 同步更新pageSize
  useEffect(() => {
    props.pageSize && $pageSize(props.pageSize);
  }, [props.pageSize]);

  // 改变触发onChange
  useEffect(() => {
    if (shouldChange.current) {
      props.onChange &&
        props.onChange({
          current,
          pageSize,
        });
      shouldChange.current = false;
    }
  }, [current, pageSize]);

  // 计算当前段及总页数
  useEffect(() => {
    const pageCount = Math.ceil(total / pageSize);
    $pageCount(pageCount);
    let now = current;
    if (pageCount && now > pageCount) {
      now = pageCount;
      $current(now);
      $jumpCurrent(now);
      shouldChange.current = true;
      return;
    }
    let section = '' + (pageSize * (current - 1) + 1);
    if (pageSize * (current - 1) + 1 < total) {
      if (pageSize * current > total) {
        section += '-' + total;
      } else {
        section += '-' + pageSize * current;
      }
    }
    $section(section);
  }, [total, current, pageSize]);

  // 跳页页码变化
  const iptChange = useCallback(
    (e: { target: HTMLInputElement }) => {
      if (e.target.value === '') {
        $jumpCurrent('');
        return;
      }
      let value = parseInt(e.target.value);
      if (value && value > 0 && value <= pageCount) {
        if (value > 0 && value <= pageCount) {
          $jumpCurrent(value);
        }
      }
    },
    [pageCount],
  );

  // 跳页
  const jumpPage = useCallback(
    (e: any) => {
      let iptv = e.target as HTMLInputElement;
      let value = parseInt(iptv.value);
      if (value && value > 0) {
        if (value <= pageCount) {
          $current(Number(value));
        } else {
          $current(pageCount);
          $jumpCurrent(pageCount);
        }
        shouldChange.current = true;
      }
      iptObj.current?.blur();
    },
    [pageCount],
  );

  // 跳页输入框失去焦点
  const jumpInputBlur = useCallback(
    (e: any) => {
      if (e.target.value === '') {
        $jumpCurrent(current);
      }
    },
    [current],
  );

  // 上一页
  const pre = () => {
    $current((pre) => {
      $jumpCurrent(pre - 1);
      shouldChange.current = true;
      return pre - 1;
    });
  };

  // 下一页
  const next = () => {
    $current((pre) => {
      $jumpCurrent(pre + 1);
      shouldChange.current = true;
      return pre + 1;
    });
  };

  return (
    <>
      {total ? (
        <div
          className={
            props.className
              ? `${'inbiz-pagination-samll'} ${props.className}`
              : 'inbiz-pagination-samll'
          }
          style={props.style}
        >
          <div className={'left-content'}>
            <Select
              size="small"
              value={pageSize}
              dropdownClassName={'inbiz-component-pagination-samll-dropdown'}
              suffixIcon={
                <CaretDownOutlined
                  style={{ color: '#ddd', pointerEvents: 'none' }}
                />
              }
              onChange={(e: number) => {
                const pageCount = Math.ceil(total / e);
                if (pageCount && current <= pageCount) {
                  shouldChange.current = true;
                }
                $pageSize(e);
              }}
            >
              {Array.isArray(props.options) && props.options.length ? (
                props.options.map((item) => {
                  return (
                    <Option value={item} key={item}>
                      {item}
                    </Option>
                  );
                })
              ) : (
                <>
                  <Option value={10} key={10}>
                    {10}
                  </Option>
                  <Option value={20} key={20}>
                    {20}
                  </Option>
                  <Option value={30} key={30}>
                    {30}
                  </Option>
                  <Option value={40} key={40}>
                    {40}
                  </Option>
                  <Option value={50} key={50}>
                    {50}
                  </Option>
                </>
              )}
            </Select>
          </div>
          <div className={'right-content'}>
            <Space>
              <span className={'section-text'}>
                {section} / {total}
              </span>
              <Button
                type="text"
                size="small"
                onClick={pre}
                disabled={current <= 1}
                title={getMessage('Pagination.before')} // 上一页
              >
                <LeftOutlined />
              </Button>
              <Input
                style={{ width: 45, textAlign: 'center' }}
                size="small"
                ref={iptObj}
                value={jumpCurrent}
                onChange={iptChange}
                onPressEnter={jumpPage}
                onBlur={jumpInputBlur}
              />
              <span className={'pagecount-text'}>/ {pageCount} </span>
              <Button
                type="text"
                size="small"
                onClick={next}
                disabled={current >= pageCount}
                title={getMessage('Pagination.after')} // 下一页
              >
                <RightOutlined />
              </Button>
            </Space>
          </div>
        </div>
      ) : null}
    </>
  );
};

export default ModalPagination;
